<?php


namespace Beerus\Modules\Wiki\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\wiki\MGoodsAlbum;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class GoodsAlbumController extends Controller
{
    const PAGE_SIZE = 20;
    protected $list_title = '好物专辑管理';
    protected $create_title = '新增好物专辑';
    protected $modify_title = '修改好物专辑';
    protected $list_url = '';
    protected $where = [];

    public function __construct()
    {
        $this->list_url = route('goodsAlbum.list');
        parent::__construct();
    }

    public function index(Request $request, Content $content)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 20);
        $limit = [
            'LIMIT' => [
                ($page - 1) * $pageSize,
                $pageSize
            ]
        ];
        $order = MGoodsAlbum::order();
        // 处理查询条件
        if ($id = $request->input('id', '')) $this->where['id'] = explode(',', $id);
        if ($title = $request->input('title', '')) $this->where['title[~]'] = $title;
        if ($start_time = $request->input('start_time', '')) $this->where['start_time[>=]'] = strtotime($start_time);

        $total = (int)MGoodsAlbum::count($this->where);
        $list = (array)MGoodsAlbum::select('*', $this->where + $limit + $order);

        $gridModel = new pGridDataModel($list, $total, ['perPage' => $pageSize]);

        $grid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel) {
            $grid->paginate($gridModel->getPerPage());
            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 3, function (Grid\Filter $filter) {
                    $filter->equal('id', '专题ID');
                });
                $filter->column(1 / 3, function (Grid\Filter $filter) {
                    $filter->equal('title', '专题名称');
                });
                $filter->column(1 / 3, function (Grid\Filter $filter) {
                    $filter->equal('start_time', '上线时间')->datetime();
                });
                if ($this->where) $filter->expand();//默认展开
            });

            $grid->column('id', '专题ID');
            $grid->column('title', '专题名称');
            $grid->column('start_status', '上线状态')->display(function ($value, Grid\Column $column) {
                $map = [
                    '未上线' => 'primary',
                    '已上线' => 'success',
                    '已下线' => 'warning',
                ];
                return $column->label($map[$value]);
            });
            $grid->column('wiki_count', '好物数量');
            $grid->column('remark', '备注');
            $grid->column('start_time', '上线时间');
            $grid->column('admin_id', '操作人')->display(function () {
                return $this->admin_id ? Admin::user()->find($this->admin_id)->name : '-';
            });

            $grid->disableExport();
            $grid->disableRowSelector();

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                if ($actions->row->start_status == '已下线') {
                    $actions->prepend('<a class="act fa fa-arrow-up" href="javascript:;"  data-id="' . $actions->row->id . '" data-action="online">上线</a>');
                } else {
                    $actions->prepend('<a class="act fa fa-toggle-up" href="javascript:;"  data-id="' . $actions->row->id . '" data-action="top">置顶</a>');
                    $actions->prepend('<a class="act fa fa-close" href="javascript:;"  data-id="' . $actions->row->id . '" data-action="offline">下线</a>');
                }

            });
        });

        Admin::script($this->indexScript());

        return $content->header($this->list_title)->breadcrumb(['text' => $this->list_title])->row($grid);
    }

    public function save(Request $request)
    {
        $params = $request->all();

        try {
            while (true) {
                $id = $params['id'] ?? '0';
                $wiki = $params["wiki"] ? str_replace("，", ",", trim($params["wiki"])) : '';
                $wiki = str_replace(' ', '', $wiki);
                $wikiIds = explode(',', $wiki);
                $wikiIds = array_filter(array_unique($wikiIds));
                if (empty($wikiIds)) {
                    throw new \Exception('请填写正确格式的商品id');
                }
                $wiki = implode(',', $wikiIds);
                $data = [
                    'title' => $params['title'] ?? '',
                    'color' => $params['color'] ?? '',
                    'subtitle' => $params['subtitle'] ?? '',
                    'subtitle_color' => $params['subtitle_color'] ?? '',
                    'pic' => $params['pic'] ?? '',
                    'icon' => $params['icon'] ?? '',
                    'start_time' => strtotime($params['start_time'] ?? ''),
                    'remark' => $params['remark'] ?? '',
                    'wiki' => $wiki,
                    'admin_id' => Admin::user()->id,
                    'edittime' => time(),
                ];
                if ($id > 0) {
                    $info = MGoodsAlbum::getInfo($id);
                    $oldWikiIds = $info['wiki'] ? explode(',', $info['wiki']) : [];
                    MGoodsAlbum::update($data, ['id' => $id]);
                    $newWikiIds = explode(',', $wiki);
                    $delWikiIds = array_diff($oldWikiIds, $newWikiIds);
                    break;
                }
                $data['addtime'] = time();
                MGoodsAlbum::insert($data);
                $id = MGoodsAlbum::id();
                break;
            }

            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect($this->list_url)->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败,' . $e->getMessage()
            ]);
            return back()->withInput()->with(compact('error'));
        }
    }

    public function create(Content $content, $id = 0)
    {
        $info = [
            'color' => '#6B1F13',
            'subtitle_color' => '#C49995',
            'pic' => 'a6cda30tr0e60TL00r58841',
            'icon' => '192bf307f02l0xE00r5882t',
            'start_time' => date("Y-m-d", strtotime('1 day')),
        ];
        if ($id > 0) {
            $info = MGoodsAlbum::getInfo($id);
        }

        $form = new Form($info);
        $form->hidden('id');
        $form->text('title', '专题名称')->required();
        $form->color('color', '专题名称字体颜色');
        $form->text('subtitle', '专辑描述');
        $form->color('subtitle_color', '专题描述字体颜色');
        $form->imgUpload('pic', '背景图');
        $form->imgUpload('icon', '角标');
        $form->datetime('start_time', '上线时间')->required();
        $form->textarea('wiki', '商品id')->placeholder('多个商品id使用英文,分隔')->help('多个商品id使用英文,分隔');
        $form->textarea('remark', '备注信息');
        $form->action(route('goodsAlbum.save'));

        Admin::script($this->getBaseInfoScript());
        $title = $id ? $this->modify_title : $this->create_title;
        return $content->header($title)
            ->breadcrumb(
                ['text' => $this->list_title, 'url' => $this->list_url],
                ['text' => $title]
            )
            ->row($form);
    }

    public function act(Request $request)
    {
        $id = $request->input('id', 0);
        $act = $request->input('act', 'offline'); //top offline online
        $code = 0;
        try {
            switch ($act) {
                case 'online':
                    $msg = '上线成功';
                    if (MGoodsAlbum::isDel($id)) {
                        MGoodsAlbum::online($id);
                    }
                    break;
                case 'offline':
                    $msg = '下线成功';
                    if (!MGoodsAlbum::isDel($id)) {
                        MGoodsAlbum::offline($id);
                        $info = MGoodsAlbum::getInfo($id);
                        $delWikIds = explode(',', $info['wiki']);
                    }
                    break;
                case 'top':
                    $msg = '置顶成功';
                    MGoodsAlbum::top($id);
                    break;
                default:
                    $msg = 'nothing';
                    break;
            }

        } catch (\Exception $e) {
            $code = 1;
            $msg = $e->getMessage();
        }

        $response = [
            'code' => $code,
            'msg' => $msg,
        ];
        return response()->json($response);
    }

    private function indexScript()
    {
        $url = route('goodsAlbum.act');
        return <<<EOF
let close_url = '$url';
$('.act').unbind('click').click(function(){
    let id= $(this).data('id');
    let act= $(this).data('action');
    let params = {id:id, act:act};
    if (act == 'offline') {
        layer.confirm('是否下线该专辑', {btn: ['是', '否']}, function (index) {
            $.post(close_url, params , function (rs) {
                toastr.success(rs.msg, null, {
                    timeOut : 1000
                });
                if (rs.code == 0) {
                   $.admin.reload();
                }
            });
            layer.close(layer.index);
        });
    } else {
        $.post(close_url, params , function (rs) {
            toastr.success(rs.msg, null, {
                timeOut : 1000
            });
            if (rs.code == 0) {
                $.admin.reload();
            }
        });
    }
})
EOF;
    }

    private function getBaseInfoScript()
    {
        return <<<EOF
$('.shop_id').blur(function(){
    var shop_id = $(this).val();
    var url = 'getbasicinfo?shop_id=' + $(this).val()
    $.get(url, function (result) {
        if (result.code == 1) {
            $('.shop_name').val(result.msg)
        }
    });  
})
EOF;
    }
}